import os
import re
import random
import time
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.keys import Keys
from core.captcha_solver import CaptchaSolver as CS
from core.baidu_cuttlefish import BaiduCuttlefish as BC
from core.api_client import ApiClient as AC
from selenium.common.exceptions import ElementClickInterceptedException
class TaskExecutor:
    def __init__(self, driver, folder_path=None, files_list = [],upload_limit=100, task_type=1, ac=None,account=None):
        """
        初始化TaskExecutor对象。

        :param driver: 打开到指定页面的浏览器对象
        :param folder_path: 文档所在文件夹路径，默认为None；
        :param files_lis:  和文件夹路径二选一
        :param upload_limit: 上传次数限制，默认为10
        :param task_type: 任务类型，1表示vip文档上传，2表示定产vip上传
        :param ac: API客户端，负责和服务器通讯，用于任务2
        """
        self.driver = driver
        self.folder_path = folder_path or self._default_folder_path(task_type)
        self.files_list = files_list # or self._get_files_list(self.folder_path)
        self.upload_limit = upload_limit
        self.error_num = 0  # 错误次数
        self.ac = ac
        self.task_able = True
        self.task_type = task_type
        self.account = account
        self.refresh_page = 100
        if account:
            self.bc = BC(self.account.get('cookie'))
        if task_type == 2 or task_type == 3:
            #获取哪个页面刷新了
            self.refresh_page= self.bc.get_which_task_page_able_return()
        if self.task_type == 1:
            self.upload_vip_file()
        elif self.task_type == 2:
            self.upload_vip3_file()
        elif self.task_type == 3:
            self.upload_vip3_file()

    def _default_folder_path(self, task_type):
        """
        返回默认的文件夹路径。

        :param task_type: 任务类型
        :return: 默认文件夹路径
        """
        folder_name = "vip_files" if task_type == 1 else "task_files"
        return os.path.join(os.getcwd(), folder_name)
    
    def _which_page_is_able(self):
        pass
    def upload_vip_file(self):
        """
        上传VIP文档任务。
        """
        print("========================================================================================")
        print(f"VIP文档任务开始，计划上传{self.upload_limit}次，文件目录为 {self.folder_path}")
        print("========================================================================================")
        files_list = self._get_files_list(self.folder_path)
        if not files_list:
            print("文件夹中没有找到文件，上传任务结束。")
            return

        random.shuffle(files_list)
        for count, file_path in enumerate(files_list, 1):
            if not self.task_able:
                print("今日上传任务已完成")
                break
            print(f"----------<{self.account.get('uname')}>开始上传第 {count} 个文档----------")
            if not self.upload_file(file_path):
                # print("终止文件上传过程，请检查下原因。")
                continue
                # break
            print(f"<{self.account.get('uname')}>已完成 {count} 个文档上传")
            time.sleep(random.randint(5, 10))
            if count >= self.upload_limit:
                print(f"==========================================上传完成累计{count} 个==============================================")
                break

    def _get_files_list(self, folder_path):
        """
		获取文件夹中的文件列表。

		:param folder_path: 文件夹路径
		:return: 文件列表
		"""
        if self.files_list:
            return self.files_list
        files_list = []
        for root, dirs, files in os.walk(folder_path):
            for file in files:
                files_list.append(os.path.join(root, file))
        return files_list

    def upload_file(self, file_path):
        """
		上传文件。

		:param file_path: 文件路径
		:return: 是否成功上传
		"""
        if self.error_num == 5:
            print("连续出错5次,请分析原因")
            return False

        try:
            file_input = WebDriverWait(self.driver, 20).until(
                EC.presence_of_element_located((By.CSS_SELECTOR, ".file-selector-input"))
            )
        except TimeoutException:
            self.driver.save_screenshot('未找到vip上传表单.png')
            data = {
                "uid": self.account.get('uid'),
                "is_vipdoc_finish": 1,
            }
            res = self.ac.post_data(endpoint="/api/wenku/account/updateByCond", data=data)
            self.task_able = False
            print("今日VIP任务已完成")
            return True

        # file_input.send_keys(file_path)#upload-doc#upload-doc > div
        # add_button = self.driver.get_element_by_id("upload-doc")
        # add_button = self.driver.find_element(By.ID, 'upload-doc')
        # add_button.click()
        try:
            file_input.send_keys(file_path)
        except Exception as e:
            print(f"send_keys失败：{e}")
            print("元素的outerHTML:", file_input.get_attribute('outerHTML'))
            self.driver.save_screenshot('send_keys失败.png')
            self.error_num += 1
            return False
        time.sleep(3)

        if "seccaptcha.baidu.com" in self.driver.current_url:
            print("==============================开始处理验证码==============================")
            self.handle_captcha()
            return self.upload_file(file_path)

        try:
            WebDriverWait(self.driver, 30).until(
                EC.invisibility_of_element_located((By.CSS_SELECTOR, ".el-loading-mask"))
            )
        except TimeoutException:
            print("等待遮罩层消失超时，已保存错误截图{time.time()}，即将重试。")
            self.driver.save_screenshot(f'一直显示上传中{time.time()}.png')
            self.driver.refresh()
            self.error_num += 1
            return self.upload_file(file_path)
        try:
            radio_select = WebDriverWait(self.driver, 60).until(
                EC.element_to_be_clickable((By.CSS_SELECTOR, ".el-radio:nth-child(3) .el-radio__inner"))
            )
            self.driver.execute_script("arguments[0].scrollIntoView();", radio_select)
            time.sleep(1)
            radio_select.click()
        except TimeoutException:
            print(f"文件检查无效，请核实{time.time()}")
            self.driver.save_screenshot(f'文件检查无效{time.time()}.png')
            self.error_num += 1
            self.driver.refresh()
            return True
        except ElementClickInterceptedException:
            print(f"元素被遮挡，尝试通过JavaScript点击{time.time()}")
            # self.driver.save_screenshot(f'元素被遮挡尝试通过JavaScript点击{time.time()}.png')
            self.driver.execute_script("arguments[0].click();", radio_select)
        time.sleep(1)
        if not self._submit_upload_form(file_path):
            # return self.upload_file(file_path)
            return False
        return True

    def _submit_upload_form(self, file_path):
        """
        提交上传表单。

        :param file_path: 文件路径
        :return: 是否成功提交
        """
        if "seccaptcha.baidu.com" in self.driver.current_url:
            print("==============================开始处理验证码==============================")
            self.handle_captcha()
            return False

        try:
            submit_button = WebDriverWait(self.driver, 20).until(
                EC.element_to_be_clickable((By.CSS_SELECTOR, ".doc-upload-btn-bar > .el-button > span"))
            )
            # print("确认上传按钮可以用了，现在截图备查")
            # self.driver.save_screenshot('确认上传按钮可以用了.png')
            submit_button.click()
            time.sleep(2)
            # self.driver.save_screenshot('确认上传按钮可以用了1.png')
        except TimeoutException:
            print("确认提交按钮无法点击，请查看截图")
            self.driver.save_screenshot('确认提交按钮无法点击.png')
            self.error_num += 1
            time.sleep(10)
            self.driver.refresh()
            time.sleep(10)
            return False

        try:
            success_dialog = WebDriverWait(self.driver, 20).until(
                EC.presence_of_element_located((By.CSS_SELECTOR, ".upload-dialog-footer > .el-button"))
            )
            success_dialog.click()
            time.sleep(2)
            if "/commodityManage/documentation" in self.driver.current_url:
                os.remove(file_path)
                print(f"{file_path} 上传成功并已删除！")
                uid = self.account.get('uid')
                # print(uid)
                if self.task_type == 1:
                    self.ac.get_data(endpoint=f"/api/wenku/account/updateAddVipNum?uid={uid}")
                return 1
            else:
                error_element = WebDriverWait(self.driver, 10).until(
                    EC.presence_of_element_located((By.CSS_SELECTOR, ".error-tip"))
                )
                self.driver.save_screenshot(f'确认下情况,点击后未跳转,错误信息：{error_element.text}.png')
                self.driver.refresh()
                time.sleep(3)

        except Exception as e:
            error_element = WebDriverWait(self.driver, 10).until(
                EC.presence_of_element_located((By.CSS_SELECTOR, ".error-tip"))
            )
            self.driver.save_screenshot(f'确认下情况,点击后未跳转,错误信息111：{error_element.text}.png')
            print(f"{file_path}上传失败,点击确认上传按钮后出现错误，请查看截图:{e}")
            self.driver.save_screenshot('点击确认上传按钮后出现错误，请查看截图.png')
            os.remove(file_path)
            self.error_num += 1
            time.sleep(10)
            self.driver.refresh()
            time.sleep(10)
            return False
        return True

    #############################################以下是原力任务##################################################
    def upload_vip2_file(self):
        """
        上传定产VIP文档任务。
        """
        if self.task_type == 2:
            file_list = os.listdir(self.folder_path)
        else:
            file_list = self.files_list

        random.shuffle(file_list)  # 打乱文件列表顺序
        i = 1
        for filename in file_list:
            if i >= self.upload_limit:
                print(f"==========={self.account.get('uname')}上传任务已完成==========")
                break
            if not self.task_able:
                print("===========今日任务已完成==========")
                break
            if self.task_type == 2:
                file_path = os.path.join(self.folder_path, filename)
                base_filename = os.path.splitext(filename)[0]
            else:
                file_path = filename
                # 使用os.path.splitext分割文件名和扩展名
                filename_with_ext, file_ext = os.path.splitext(file_path)
                # os.path.basename返回不包含路径的文件名
                base_filename = os.path.basename(filename_with_ext)
            # print(base_filename)
            titles = self.ac.get_data(endpoint="/api/wenku/titles/get_title_is_exist", title_name=base_filename,account_id=self.account.get('uid'))
            if not titles:
                print(f"无法在数据库中找到相关任务：{base_filename}")
                continue

            data = titles[0]
            #判断任务是否已经完成
            if data['is_finish']:
                print(f"<{self.account.get('uname')}>在数据库中显示任务已完成{data['is_finish']}：{data['article_name']}")
                # continue
            if not self.bc.check_task_is_available(data):
                print(f"<{self.account.get('uname')}>实时查询任务已完成：{data['article_name']}")
                if not data['is_finish']:
                    self.ac.get_data(endpoint="/api/wenku/titles/finish_by_others",id=data['id'])
                time.sleep(5)
                continue
            else:
                if data['is_finish'] == 2:
                    print(f"<{self.account.get('uname')}>非常奇怪的事发生了了了了理论了了理论了理论了了理论--------------------------------------------------------------------：{data['article_name']}")

            print("----------------------------------------------------------------")
            print(f"<{self.account.get('uname')}>开始进行任务：{data['article_name']}")
            # 优化：返回1、2、3分别赋值，1为成功，10为跳过，20结束任务，30为重试
            res = self._process_vip2_task(data, file_path)
            if res == 20:
                break
            elif res == 10 or res == 30:
                continue
            elif res == 1:
                if self.task_type == 2 or self.task_type == 3:
                    print(f"===================<{self.account.get('uname')}>已完成第{i}个任务====================")
                    if self.bc.get_is_task_finish_and_return():
                        print(f"-------------------------<{self.account.get('uname')}>今日任务已完成-------------------------")
                        self.task_able = False
                        data = {
                            "uid": self.account.get('uid'),
                            "is_task_finish": 1,
                        }
                        self.account['is_task_finish']= 1
                        res = self.ac.post_data(endpoint="/api/wenku/account/updateByCond", data=data)
                        return 0
                else:
                    print(f"===================<{self.account.get('uname')}>已完成任务<<{data['article_name']}>>====================")
                i += 1


    def _process_vip2_task(self, data, file_path):
        """
        处理定产VIP任务。
        :param data: 任务数据--数据库中的那条数据
        :param filename: 文件名
        :return: 任务是否成功完成
        """
        err_num = 0
        while True:
            time.sleep(10)
            if not self.task_able:
                print("===========今日任务已完成，结束任务==========")
                return 20
            if err_num >= 5:
                print("上传累计错误5次，跳过这个任务")
                return 10
            # 如果找不到导航，则重试
            if not self._navigate_to_task_page(data):
                err_num += 1
                return 10
                # self.driver.refresh()
                # time.sleep(5)
                # continue
            res = self._upload_vip2_file(data, file_path)
            if res == 30:
                err_num += 1
                self.driver.refresh()
                time.sleep(5)
                continue
            else:
                return res
            # if not self._upload_vip2_file(data, file_path):
            #     err_num += 1
            #     return False
            # return True
        # return False
    def _navigate_to_task_page(self, data):
        """
        导航到定产VIP任务页面。

        :param data: 任务数据
        :return: 是否成功导航
        """
        try:
            # containers = self.driver.find_elements(By.CSS_SELECTOR, '.privilege-item-container')
            # print(f"containers:{containers}")
            wait = WebDriverWait(self.driver, 10)  # 等待时间设置为10秒
            containers = wait.until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, '.privilege-item-container')))
            # for container in containers:
            #     print(container.text)

            if data['article_type'] < 20:
                target_index = data['article_type'] + 2
                if target_index <= len(containers):
                    # print("准备点击")
                    containers[target_index - 1].click()
            else:
                containers[0].click()
            print(f"<{self.account.get('uname')}>---切换到分类，分类标识：{data['article_type']}")
            time.sleep(5)
            try:
                pagination_input = WebDriverWait(self.driver, 20).until(
                    EC.element_to_be_clickable((By.CSS_SELECTOR, 'div.pagination input[type=number]'))
                )
                pagination_input.clear()
                pagination_input.send_keys(int(data['page_number']) + 1)
                pagination_input.send_keys(Keys.ENTER)
                pagination_input.send_keys(Keys.TAB)
                print(f"<{self.account.get('uname')}>---定位到页面，页码：{data['page_number'] + 1}")
                time.sleep(3)
                return True
            except Exception as e:
                print(f"<{self.account.get('uname')}>定位到页面失败{e}")
                return False
        except TimeoutException:
            print(f"<{self.account.get('uname')}>导航到任务页面失败{e}")
            return False

    def _upload_vip2_file(self, data, file_path):
        """
        上传定产VIP文件。

        :param data: 任务数据
        :param filename: 文件名
        :return: 是否成功上传
        """
        while True:
            try:
                doc_rows = self.driver.find_elements(By.CSS_SELECTOR, 'div.doc-wrapper div.doc-row')
                target_doc_row = doc_rows[data['page_sort_number'] - 1] if data['page_sort_number'] <= len(doc_rows) else None
                if not target_doc_row:
                    print(f"<{self.account.get('uname')}>未找到对应的文档行,马上刷新重新")
                    return 30

                title_span = target_doc_row.find_element(By.CSS_SELECTOR, '.title-line .doc-title')
                title_value = title_span.get_attribute('title')
                if title_value != data['article_name']:
                    print(f"<{self.account.get('uname')}>文档标题不对：{title_value}，马上刷新重新")
                    return 30
                # time.sleep(1000)
                status_span = target_doc_row.find_element(By.CSS_SELECTOR, '.complete-status')
                # if 'none' not in status_span.get_attribute('style').lower():
                if status_span.is_displayed():
                    if not data['is_finish']:
                        self.ac.get_data(endpoint="/api/wenku/titles/finish_by_others",id=data['id'])
                    print(f"<{self.account.get('uname')}>的{data["article_name"]}》任务已被人完成，马上进行下一个任务")
                    # print(f"更新到数据库的结果：{res}")
                    # os.remove(file_path)
                    return 10
                try:
                    file_input = target_doc_row.find_element(By.CSS_SELECTOR, '.file-selector-input') #input[type=file]
                    # 或者，获取并打印元素的outerHTML（包括元素本身的HTML）
                    # print("元素的outerHTML:", file_input.get_attribute('outerHTML'))
                except Exception:
                    self.task_able = False
                    data = {
                        "uid": self.account.get('uid'),
                        "is_task_finish": 1,
                    }
                    res = self.ac.post_data(endpoint="/api/wenku/account/updateByCond", data=data)
                    # print(f"更新到数据库的结果：{res}")
                    print(f"<{self.account.get('uname')}>未找到对应的上传表单，今日任务已完成，结束任务")
                    self.account['is_task_finish']= 1
                    return 20
                # print("找到了文件的input")
                #模拟点击
                upload_botton = target_doc_row.find_element(By.CSS_SELECTOR, '.el-button')
                upload_botton.click()
                # print("开始点击上传按钮")
                time.sleep(3)
                res = self.upload_file2(file_path, file_input,data)
                return res
            except Exception as e:
                self.driver.save_screenshot(f'上传原力任务文件《{data['article_name']}》失败{time.time()}.png')
                print(f"<{self.account.get('uname')}>上传原力任务文件《{data['article_name']}》失败{time.time()}：{e}")
                return 30


    def upload_file2(self, file_path, file_input,data):
        """
        上传定产VIP文件。

        :param file_path: 文件路径
        :param file_input: 文件输入框
        :return: 是否成功上传
        """
        file_input.send_keys(file_path)#表单赋值
        time.sleep(5)
        if "seccaptcha.baidu.com" in self.driver.current_url:
            print(f"==============================<{self.account.get('uname')}>开始处理验证码==============================")
            self.handle_captcha()
            return 30

        try:
            WebDriverWait(self.driver, 60).until(
                EC.invisibility_of_element_located((By.CSS_SELECTOR, ".el-loading-mask"))
            )
        except TimeoutException:
            print(f"<{self.account.get('uname')}>等待遮罩层消失超时，已保存错误截图，即将重试。")
            self.driver.save_screenshot(f'<{self.account.get('uname')}>一直显示上传中{time.time()}.png')
            return 30
        # time.sleep(100)
        time.sleep(5)
        #确认上传是否成功
        res = self._submit_upload2_form(file_path,data)
        return res
        # if not self._submit_upload_form(file_path):
        #     return False
        # return True


    def _submit_upload2_form(self, file_path,data):
        """
        提交上传表单。

        :param file_path: 文件路径
        :return: 是否成功提交
        """
        if "seccaptcha.baidu.com" in self.driver.current_url:
            print("==============================开始处理验证码==============================")
            self.handle_captcha()
            return 30

        try:
            submit_button = WebDriverWait(self.driver, 20).until(
                EC.element_to_be_clickable((By.CSS_SELECTOR, ".doc-upload-btn-bar > .el-button > span"))
            )
            time.sleep(1)
            submit_button.click()
            # self.driver.save_screenshot(f'上传确认截图{time.time()}.png')
        except TimeoutException:
            print(f"<{self.account.get('uname')}>确认提交按钮无法点击，请查看截图{time.time()}")
            self.driver.save_screenshot(f'<{self.account.get('uname')}>确认提交按钮无法点击{time.time()}.png')
            return 30

        try:
            success_dialog = WebDriverWait(self.driver, 20).until(
                EC.presence_of_element_located((By.CSS_SELECTOR, ".upload-dialog-footer > .el-button"))
            )
            time.sleep(2)
            success_dialog.click()
            time.sleep(3)
            if "taskCenter/majorTask" in self.driver.current_url:
                os.remove(file_path)
                print(f"{file_path} 上传成功并已删除！")
                # print(self.account)
                uid = self.account.get('uid')
                if self.task_type == 2 or self.task_type == 3:
                    self.ac.get_data(endpoint="/api/wenku/titles/finish_by_me", id=data['id'])
                    self.ac.get_data(endpoint=f"/api/wenku/account/updateAddTaskNum?uid={uid}")
                return 1
            else:
                print(f"未知原因，请查看截图{time.time()}")
                self.driver.save_screenshot(f'未知原因，请查看截图{time.time()}.png')
                return 10
        except TimeoutException:
            print(f"{file_path}上传失败{time.time()}")
            self.driver.save_screenshot(f'确认上传后出错{time.time()}.png')
            return 10

    def upload_vip3_file(self):
        """
        上传定产VIP文档任务。
        """
        if self.refresh_page == 100:
            print("----未发现刷新的任务页面-----")
            return

        if self.task_type == 2:
            if not os.path.exists(self.folder_path):
                print(f"{self.folder_path} 文件夹不存在，请检查！")
                return
            file_list = os.listdir(self.folder_path)
        else:
            file_list = self.files_list

        random.shuffle(file_list)  # 打乱文件列表顺序
        i = 1
        for filename in file_list:
            if i >= self.upload_limit:
                print(f"==========={self.account.get('uname')}上传任务已完成==========")
                break
            if not self.task_able:
                print("===========今日任务已完成==========")
                break
            if self.task_type == 2:
                file_path = os.path.join(self.folder_path, filename)
                base_filename = os.path.splitext(filename)[0]
            else:
                file_path = filename
                # 使用os.path.splitext分割文件名和扩展名
                filename_with_ext, file_ext = os.path.splitext(file_path)
                # os.path.basename返回不包含路径的文件名
                base_filename = os.path.basename(filename_with_ext)
            # print(base_filename)
            titles = self.ac.get_data(endpoint="/api/wenku/titles/get_title_is_exist", title_name=base_filename,account_id=self.account.get('uid'))
            if not titles:
                print(f"无法在数据库中找到相关任务：{base_filename}")
                continue

            data = titles[0]
            #判断任务是否已经完成
            if data['is_finish']:
                print(f"<{self.account.get('uname')}>在数据库中显示任务已完成{data['is_finish']}：{data['article_name']}")
                # continue
            # if not self.bc.check_task_is_available(data):
            #     print(f"<{self.account.get('uname')}>实时查询任务已完成：{data['article_name']}")
            #     if not data['is_finish']:
            #         self.ac.get_data(endpoint="/api/wenku/titles/finish_by_others",id=data['id'])
            #     time.sleep(5)
            #     continue
            # else:
            #     if data['is_finish'] == 2:
            #         print(f"<{self.account.get('uname')}>非常奇怪的事发生了了了了理论了了理论了理论了了理论--------------------------------------------------------------------：{data['article_name']}")

            print("----------------------------------------------------------------")
            print(f"<{self.account.get('uname')}>开始进行任务：{data['article_name']}")
            # 优化：返回1、2、3分别赋值，1为成功，10为跳过，20结束任务，30为重试
            res = self._process_vip3_task(data, file_path)
            if res == 20:
                break
            elif res == 10 or res == 30:
                continue
            elif res == 1:
                if self.task_type == 2 or self.task_type == 3:
                    print(f"===================<{self.account.get('uname')}>已完成第{i}个任务====================")
                    if self.bc.get_is_task_finish_and_return():
                        print(f"-------------------------<{self.account.get('uname')}>今日任务已完成-------------------------")
                        self.task_able = False
                        data = {
                            "uid": self.account.get('uid'),
                            "is_task_finish": 1,
                        }
                        self.account['is_task_finish']= 1
                        res = self.ac.post_data(endpoint="/api/wenku/account/updateByCond", data=data)
                        return 0
                else:
                    print(f"===================<{self.account.get('uname')}>已完成任务<<{data['article_name']}>>====================")
                i += 1


    def _process_vip3_task(self, data, file_path):
        """
        处理定产VIP任务。
        :param data: 任务数据--数据库中的那条数据
        :param filename: 文件名
        :return: 任务是否成功完成
        """
        err_num = 0
        while True:
            time.sleep(10)
            if not self.task_able:
                print("===========今日任务已完成，结束任务==========")
                return 20
            if err_num >= 5:
                print("上传累计错误5次，跳过这个任务")
                return 10
            # 如果找不到导航，则重试
            if not self._navigate_to_task3_page(data):
                err_num += 1
                return 10
                # self.driver.refresh()
                # time.sleep(5)
                # continue
            res = self._upload_vip3_file(data, file_path)
            if res == 30:
                err_num += 1
                self.driver.refresh()
                time.sleep(5)
                continue
            else:
                return res
            # if not self._upload_vip2_file(data, file_path):
            #     err_num += 1
            #     return False
            # return True
        # return False
    def _navigate_to_task3_page(self, data):
        """
        导航到定产VIP任务页面。

        :param data: 任务数据
        :return: 是否成功导航
        """
        try:
            wait = WebDriverWait(self.driver, 10)  # 等待时间设置为10秒
            containers = wait.until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, '.privilege-item-container')))
            # print(self.refresh_page)
            if self.refresh_page != 99:
                containers[self.refresh_page + 1].click()
            time.sleep(5)

            try:
                WebDriverWait(self.driver, 10).until(
                    EC.presence_of_element_located((By.CSS_SELECTOR, '.doc-row'))
                )
                print("找到了任务列表")
                try:
                    # 显式等待直到元素出现
                    wait = WebDriverWait(self.driver, 10)  # 等待最多10秒
                    element = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, ".file-selector-input")))
                    print("找到了文件选择框")
                    return True
                except Exception as e:
                    print(f"上传表单未找到: {e}")
                    data1 = {
                        "uid": self.account.get('uid'),
                        "is_task_finish": 1,
                    }
                    res = self.ac.post_data(endpoint="/api/wenku/account/updateByCond", data=data1)
                    self.task_able = False
                    return False
            except TimeoutException:
                return False  # 如果超时，则继续下一个容器
        except TimeoutException as e:
            print(f"<{self.account.get('uname')}>导航到任务页面失败{e}")
            return False

    def _upload_vip3_file(self, data, file_path):
        """
        上传定产VIP文件。

        :param data: 任务数据
        :param filename: 文件名
        :return: 是否成功上传
        """
        doc_rows = self.driver.find_elements(By.CSS_SELECTOR, 'div.doc-wrapper div.doc-row')
        target_doc_row = doc_rows[8]
        file_input = target_doc_row.find_element(By.CSS_SELECTOR, '.file-selector-input')  # input[type=file]
        file_input.send_keys(file_path)
        # file_input.send_keys(r"C:\Users\Administrator\Desktop\july\doc_files\task_files\中国戏曲蓬勃发展作文英语.docx")
        res = self.upload_file3(file_path, file_input, data)
        return res


    def upload_file3(self, file_path, file_input,data):
        """
        上传定产VIP文件。

        :param file_path: 文件路径
        :param file_input: 文件输入框
        :return: 是否成功上传
        """
        time.sleep(5)
        if "seccaptcha.baidu.com" in self.driver.current_url:
            print(
                f"==============================<{self.account.get('uname')}>开始处理验证码==============================")
            self.handle_captcha()
            return 30
        # 如何成功跳转，则获取当前的url，例子是:https://cuttlefish.baidu.com/shopmis?_wkts_=1724710643497#/taskCenter/majorDoc/upload?taskName=abc&targetVal=1&queryId=xyz
        # 把url查询参数中的taskName的值abc（示例值）替换为data['article_name']，queryId的xyz（示例值）替换为data['query_id']
        # 获取当前 URL
        current_url = self.driver.current_url
        # 解析 URL
        # 第二步：提取第二个问号及之前的部分
        base_url_match = re.search(r'^(https://[^?]+(?:\?.*?))\?', current_url)
        if base_url_match:
            base_part = base_url_match.group(1) + '?'
        else:
            base_part = current_url
        # 第三步：拼接新的查询字符串
        # data = {
        #     "article_name": "中国戏曲蓬勃发展作文英语",
        #     "query_id": "ae800fc308a1284ac8504359"
        # }
        new_query_string = f"taskName={data['article_name']}&targetVal=1&queryId={data['query_id']}"
        # 构建新的 URL
        new_url = base_part + new_query_string
        print(new_url)
        time.sleep(5)
        # 跳转到新 URL
        self.driver.get(new_url)
        time.sleep(10)
        try:
            WebDriverWait(self.driver, 60).until(
                EC.invisibility_of_element_located((By.CSS_SELECTOR, ".el-loading-mask"))
            )
        except TimeoutException:
            print(f"<{self.account.get('uname')}>等待遮罩层消失超时，已保存错误截图，即将重试。")
            self.driver.save_screenshot(f'<{self.account.get('uname')}>一直显示上传中{time.time()}.png')
            return 30
        # time.sleep(100)
        time.sleep(5)
        # 确认上传是否成功
        res = self._submit_upload3_form(file_path, data)
        return res


    def _submit_upload3_form(self, file_path,data):
        """
        提交上传表单。

        :param file_path: 文件路径
        :return: 是否成功提交
        """
        if "seccaptcha.baidu.com" in self.driver.current_url:
            print("==============================开始处理验证码==============================")
            self.handle_captcha()
            return 30

        try:
            submit_button = WebDriverWait(self.driver, 20).until(
                EC.element_to_be_clickable((By.CSS_SELECTOR, ".doc-upload-btn-bar > .el-button > span"))
            )
            time.sleep(1)
            submit_button.click()
            # self.driver.save_screenshot(f'上传确认截图{time.time()}.png')
        except TimeoutException:
            print(f"<{self.account.get('uname')}>确认提交按钮无法点击，请查看截图{time.time()}")
            self.driver.save_screenshot(f'<{self.account.get('uname')}>确认提交按钮无法点击{time.time()}.png')
            return 30

        time.sleep(2)
        self.driver.save_screenshot(f'<{self.account.get('uname')}>确认提交按钮点击后{time.time()}.png')

        try:
            success_dialog = WebDriverWait(self.driver, 20).until(
                EC.presence_of_element_located((By.CSS_SELECTOR, ".upload-dialog-footer > .el-button"))
            )
            success_dialog.click()
            time.sleep(3)
            if "taskCenter/majorTask" in self.driver.current_url:
                os.remove(file_path)
                print(f"{file_path} 上传成功并已删除！")
                # print(self.account)
                uid = self.account.get('uid')
                if self.task_type == 2 or self.task_type == 3:
                    self.ac.get_data(endpoint="/api/wenku/titles/finish_by_me", id=data['id'])
                    self.ac.get_data(endpoint=f"/api/wenku/account/updateAddTaskNum?uid={uid}")
                return 1
            else:
                print(f"未知原因2，请查看截图{time.time()}")
                self.driver.save_screenshot(f'未知原因2，请查看截图{time.time()}.png')
                os.remove(file_path)
                return 10
        except TimeoutException:
            print(f"{file_path}上传失败{time.time()}")
            self.driver.save_screenshot(f'确认上传后出错{time.time()}.png')
            return 10

    def download_vip_file(self, docs, num=0):
        random.shuffle(docs)
        # 循环访问页面并下载
        download_count = 0  # 已下载的文档数量
        max_download_count = num  # 最大下载次数限制
        for doc in docs:
            if download_count >= max_download_count:
                print("已达到最大下载次数，结束下载")
                break
            if doc['doc_status'] != 2:
                continue
            doc_id = doc['doc_id']
            if doc['doc_status'] != 2:
                continue
            timestamp = int(time.time() * 1000)  # 获取13位时间戳?{timestamp}
            url = f'https://wenku.baidu.com/view/{doc_id}.html?_wkts_={timestamp}'
            self.driver.get(url)
            time.sleep(5)
            if "seccaptcha.baidu.com" in self.driver.current_url:
                print("出现了验证码...")
                self.handle_captcha()
            time.sleep(5)
            try:
                download_button = self.driver.find_element(By.CSS_SELECTOR, 'div.drop-down + .btn-normal')
                # print(download_button)
                print(download_button.text)
                if '单篇下载' in download_button.text:
                    download_button.click()
                    print(f"第{download_count + 1}个VIP文档下载成功")
                    download_count += 1
                else:
                    if '重新下载' in download_button.text:
                        print(f"文档 {doc_id} 已经下载过")
            except Exception as e:
                print(f"文档 {doc_id} 下载失败: {e}")
            time.sleep(10)  # 等待3秒再进行下一个下载
    def handle_captcha(self):
        """
        处理验证码。
        """
        CS(self.driver)
        self.driver.refresh()
        time.sleep(5)
        return

if __name__ == "__main__":
    # 示例代码
    # driver = ...  # 初始化浏览器对象
    # TaskExecutor(driver)
    print(111)
